﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;

namespace RegionSplittor.Utils
{
	internal class ConvexHull
	{
		public static List<XYZ> Convert2ConvexHull(IList<XYZ> points)
		{
			return ConvexHull.Convert2ConvexHull(new List<XYZ>(points.Distinct(new XyzEqualityComparer(1E-06))));
		}

		private static List<XYZ> Convert2ConvexHull(List<XYZ> points)
		{
			if (points == null)
			{
				throw new System.ArgumentNullException("points == null");
			}
			XYZ xyz = points.MinBy((XYZ p) => p.X);
			List<XYZ> list = new List<XYZ>();
			XYZ xyz2 = xyz;
			XYZ rv2 = XYZ.BasisY.Negate();
			do
			{
				list.Add(xyz2);
				XYZ wp = xyz2;
				XYZ rv = rv2;
				xyz2 = points.MinBy(delegate(XYZ p)
				{
					double num = (p - wp).AngleOnPlaneTo(rv, XYZ.BasisZ);
					if (num < 1E-10)
					{
						num = Math.PI*2;
					}
					return num;
				});
				rv2 = wp - xyz2;
			}
			while (xyz2 != xyz);
			list.Reverse();
			return list;
		}
	}
}
